#include "face_server.h"
#include "ui_face_server.h"
#include <opencv2/opencv.hpp>
#include <QMessageBox>
#include <QDateTime>
#include <QThread>
#include <QSqlQuery>
#include <QSqlError>

Face_Server::Face_Server(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Face_Server)
{
    ui->setupUi(this);
    //qtcpServer当有客户端连会发送newconnection
    connect(&mserver,&QTcpServer::newConnection,this,&Face_Server::accept_client);
    mserver.listen(QHostAddress::Any,8080);

    bsize = 0;
    //给模型绑定表格
    model.setTable("employee");

    //创建线程
    QThread *thread = new QThread();
    //把QFaceObject对象移动到thread线程中执行
    fobj.moveToThread(thread);
    //启动线程
    thread->start();

    connect(this,&Face_Server::query,&fobj,&FaceObject::face_query);
    //关联QFaceObject对象里面的send_faceid信号
    connect(&fobj,&FaceObject::send_faceid,this,&Face_Server::recv_faceid);
}

Face_Server::~Face_Server()
{
    delete ui;
}

void Face_Server::accept_client()
{
    //获取与客户端通信的套接字
    msocket = mserver.nextPendingConnection();
    QMessageBox::information(this,"提示","客户端连接成功");

    //当客户端有数据到达会发送readyRead信号
    connect(msocket,&QTcpSocket::readyRead,this,&Face_Server::read_data);
}

//读取客户端发送的数据
void Face_Server::read_data()
{
    QDataStream stream(msocket);                //把套接字绑定到数据流
    stream.setVersion(QDataStream::Qt_5_14);    //设置版本

    if(bsize == 0)
    {
        if(msocket->bytesAvailable() < (qint64)sizeof(bsize)) return;
        //采集数据的长度
        stream >> bsize;
    }
    if(msocket->bytesAvailable() < bsize)   //说明数据还没有发送完成，返回继续等待
    {
        return;
    }

    QByteArray data;
    stream >> data;
    bsize = 0;
    if(data.size() == 0)    //没有读取数据
    {
        return;
    }

    //显示图片
    QPixmap mmp;
    mmp.loadFromData(data,"jpg");
    mmp = mmp.scaled(ui->picLb->size());
    ui->picLb->setPixmap(mmp);

    //识别人脸
    cv::Mat faceImage;
    std::vector<uchar> decode;
    decode.resize(data.size());
    memcpy(decode.data(),data.data(),data.size());
    faceImage = cv::imdecode(decode,cv::IMREAD_COLOR);

    emit query(faceImage);
//    int faceID = fobj.face_query(faceImage);    //消耗资源较多
}

void Face_Server::recv_faceid(int64_t faceid)
{
    //  qDebug()<<"0000 "<<faceID;
    //从数据库中查询faceID对应的人脸信息
    //给模型设置过滤器
//    qDebug()<<"识别到的人脸id:"<<faceid;

    if(faceid < 0)
    {
        QString sdmsg = QString("{\"emploteeID\":\" \",\"name\":\"\",\"department\":\"\",\"time:\"\"}");
        msocket->write(sdmsg.toUtf8());     //把打包好的数据发送给客户端
        return;
    }
    model.setFilter(QString("faceID=%1").arg(faceid));
    //查询
    model.select();
    //判断是否查询到数据
    if(model.rowCount() == 1)
    {
        //工号，姓名，部门，时间
        //{"emploteeID":%1,"name":%2,department:软件,time:%3}
        QSqlRecord record = model.record(0);
        QString sdmsg = QString("{\"emploteeID\":\"%1\",\"name\":\"%2\",\"department\":\"软件\",\"time\":\"%3\"}")
                .arg(record.value("emploteeID").toString()).arg(record.value("name").toString())
                .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

        //把数据写入数据库--考勤表
        QString insertSql = QString("insert into attendance(employeeID) values('%1')").arg(record.value("employeeID").toString());
        QSqlQuery query;

        if(!query.exec(insertSql))
        {
            QString sdmsg = QString("{\"emploteeID\":\" \",\"name\":\"\",\"department\":\"\",\"time:\"\"}");
            msocket->write(sdmsg.toUtf8());     //把打包好的数据发送给客户端
            qDebug()<<query.lastError().text();
            return;
        }
        else
        {
            msocket->write(sdmsg.toUtf8());     //把打包好的数据发送给客户端
        }
    }
}

